package com.zhongxi.guoyuan.fragment.RewardCoinOrder;


import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.coinPost.LogisiticsInfoAdapter;
import com.zhongxi.guoyuan.adapter.rewardCoinOrder.RewardOrderHasNoApplyAdapter;
import com.zhongxi.guoyuan.adapter.rewardCoinOrder.RewardOrderHasNoTokenAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.coinPost.LogisiticsData;
import com.zhongxi.guoyuan.entity.coinPost.LogisiticsResult;
import com.zhongxi.guoyuan.entity.rewardcoin.RewardCoinOrderInfo;
import com.zhongxi.guoyuan.entity.rewardcoin.RewardCoinOrderResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.view.coinPostShot.CoinEvaluateActivity;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static com.zhongxi.guoyuan.R.id.listView;

/**
 * A simple {@link Fragment} subclass.
 */
public class RewardOrderHasNoTokenFragment extends BaseFragment implements AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener2<ListView> {

    private PullToRefreshListView lvList;
    private RewardOrderHasNoTokenAdapter adapter;
    private List<RewardCoinOrderInfo> data = new ArrayList<>();
    private String type;

    private int pos;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            pos = (int) msg.obj;
            switch (msg.what) {
                case 0:
                    //去评价
                    toComment();
                    break;
                case 1:
//                    看物流信息
                    showLogistics();
                    break;
            }
        }
    };
    private String infoMirr;


    /**
     * 去评价
     */
    private void toComment() {
        type = "comment";
        String id = data.get(pos).getId();
        String shopid = data.get(pos).getShopid();
        Intent intent = new Intent(getActivity(), CoinEvaluateActivity.class);
        intent.putExtra("orderid", id);
        intent.putExtra("shopid", shopid);
        intent.putExtra("mirror", infoMirr);
        intent.putExtra("flag", 1);
        startActivityForResult(intent, 998);
    }

    private ListView listView;

    private void showLogistics() {
        type = "logistics";
        Map<String, String> map = new HashMap<>();
        map.put("orderid", data.get(pos).getId());
        getServer(Url.LOGISTICS_INFO, map, "", false, null, "post");
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_order_has_no_apply, container, false);
    }

    @Override
    protected void initView() {
        super.initView();
        lvList = (PullToRefreshListView) getView().findViewById(R.id.lvList);
        lvList.setMode(PullToRefreshBase.Mode.BOTH);
        adapter = new RewardOrderHasNoTokenAdapter(context, data, handler,this);
        lvList.setAdapter(adapter);
    }

    @Override
    protected void initData() {
        super.initData();
        getOrder();
        TextView tv = new TextView(context);
        tv.setGravity(Gravity.CENTER);
        tv.setText("亲,暂时还没有数据哦!");
        tv.setTextSize(20);
        //当界面为空的时候显示的视图
        lvList.setEmptyView(tv);
    }


    private void getOrder() {
        type = "order";
        String str = "&page=" + pageNum;
        getServer(Url.REWARD_TO_COMMENT, null, str, false, null, "get");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden)
        getOrder();
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("order".equals(type)) {
                RewardCoinOrderResult result = gson.fromJson(response, RewardCoinOrderResult.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                if (pageNum == 1) {
                    data.clear();
                }
                JSONObject obj = new JSONObject(response);
                if (result.getOrderInfo() != null && result.getOrderInfo().size() > 0) {
                    List<RewardCoinOrderInfo> orderInfo = result.getOrderInfo();
                    data.addAll(orderInfo);
                    infoMirr = obj.optString("orderMirror");
                    JSONObject info = obj.optJSONObject("orderMirror");
                    adapter.setInfo(info);
                    JSONObject shopInfo = obj.optJSONObject("shopInfo");
                    adapter.setShopInfo(shopInfo);
                }
                JSONObject orderCus = obj.optJSONObject("orderCus");
                if (orderCus != null && orderCus.length() > 0) {
                    adapter.setOrderCus(orderCus);
                }
                adapter.notifyDataSetChanged();
                lvList.onRefreshComplete();
            } else if ("logistics".equals(type)) {
                LogisiticsResult result = gson.fromJson(response, LogisiticsResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                LogisiticsData logisitics = result.getData();
                showLogisticsInfo(logisitics);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private LogisiticsInfoAdapter infoAdapter;

    /**
     * 物流时间轴
     */
    private void showLogisticsInfo(LogisiticsData logisitics) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        View view = LayoutInflater.from(getContext()).inflate(R.layout.post_show_logisitics, null);
        ImageView back = (ImageView) view.findViewById(R.id.post_logisitics_back);
        TextView company = (TextView) view.findViewById(R.id.post_logisitics_company);
        TextView number = (TextView) view.findViewById(R.id.post_logisitics_number);
        ListView list = (ListView) view.findViewById(R.id.post_logisitics_list);
        TextView error = (TextView) view.findViewById(R.id.logisitics_error);
        builder.setView(view);
        final AlertDialog dialog = builder.create();
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        if (!logisitics.getState().equals("4")) {
            company.setText("快递公司:" + logisitics.getShipper());
            number.setText("运单编号:" + logisitics.getLogisticCode());
            infoAdapter = new LogisiticsInfoAdapter(getContext());
            list.setAdapter(infoAdapter);
            List<LogisiticsData.Traces> traces = logisitics.getTraces();
            Collections.reverse(traces);
            infoAdapter.setList(traces);
        } else {
            list.setVisibility(View.GONE);
            error.setVisibility(View.VISIBLE);
        }
        dialog.show();
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            if (1000 == result.getCode()) {
                showShortToast("参数错误");
            } else if (2015 == result.getCode()) {
                showShortToast("订单信息不完整");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        lvList.setOnItemClickListener(this);
        lvList.setOnRefreshListener(this);
        listView = lvList.getRefreshableView();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position - 1 == adapter.getmExpandedMenuPos()) {
            adapter.setmExpandedMenuPos(-1);
        } else {
            adapter.setmExpandedMenuPos(position - 1);
        }
        adapter.notifyDataSetChanged();
        listView.setSelection(position);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum = 1;
        getOrder();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum++;
        getOrder();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent datas) {
        super.onActivityResult(requestCode, resultCode, datas);
        if (requestCode == 998 && CoinEvaluateActivity.EVALUATE_RESULT_CODE == resultCode) {
            if (pos >= 0) {
                data.remove(pos);
                adapter.notifyDataSetChanged();
            }
        }
    }
}
